﻿package javase.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 移动文件并修改其扩展名
 * */
public class IODemo1 {

	public static void main(String[] args) throws IOException {
		moveJavaFile("tmp/java", "tmp/newjava");
	}

	public static void moveJavaFile(String srcDir, String toDir) throws IOException {
		File javaDir = new File(srcDir);
		if(!javaDir.exists()){
			javaDir.mkdirs();
		}
		//初始化一个文件到原文件夹
		copyFile(new FileInputStream(new File("src/com/javase/io/demo/IODemo1.java")),new FileOutputStream(new File(srcDir,"IODemo1.java")));
		File newJavaDir = new File(toDir);
		if(!newJavaDir.exists()){
			newJavaDir.mkdirs();
		}
		//获取所有java文件
		File[] javaFiles = javaDir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".java");
			}
		});
		for(File file:javaFiles){
			System.out.println("正在移动文件:"+file.getName());
			FileInputStream fis = new FileInputStream(file);
			//修改扩展名
			String newFileName = file.getName().replaceAll("\\.java$", ".txt");
			FileOutputStream fos = new FileOutputStream(new File(toDir,newFileName));
			copyFile(fis,fos);
			file.delete();
			System.out.println("所有文件完成移动...");
		}
	}
	//复制文件
	public static void copyFile(InputStream is, OutputStream os) throws IOException {
		int len = 0;
		byte[] buff = new byte[1024];
		while((len=is.read(buff))!=-1){
			os.write(buff, 0, len);
		}
		is.close();
		os.close();
	}
	
}
